from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated

from utils.logging_utils import log_request_response
from .models import Notification
from .serializers import NotificationSerializer
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.permissions import IsAuthenticated


from rest_framework.decorators import action
from rest_framework.response import Response


class NotificationViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = NotificationSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        # 默认按时间戳逆序排序显示通知
        return Notification.objects.filter(recipient=self.request.user).order_by('-timestamp')

    @action(detail=False, methods=['get'])
    def unread(self, request):
        """获取所有未读通知"""
        unread_notifications = self.get_queryset().filter(is_read=False)
        serializer = self.get_serializer(unread_notifications, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['get'])
    def has_unread(self, request):
        """检查是否有未读通知"""
        has_unread = self.get_queryset().filter(is_read=False).exists()
        return Response({"has_unread": has_unread})


from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response


@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def mark_notifications_as_read(request):
    # 从请求体中获取通知ID列表
    notification_ids = request.data.get('ids', [])

    # 校验ID列表是否为空
    if not notification_ids:
        return Response({"error": "请提供有效的通知ID列表"}, status=400)

    # 更新属于当前用户的指定通知为已读
    updated_count = Notification.objects.filter(id__in=notification_ids, recipient=request.user).update(is_read=True)

    return Response({'status': 'success', 'updated_count': updated_count})

@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def delete_mark_notifications(request):
    # 从请求体中获取通知ID列表
    notification_ids = request.data.get('ids', [])

    # 校验ID列表是否为空
    if not notification_ids:
        return Response({"error": "请提供有效的通知ID列表"}, status=400)

    # 删除属于当前用户的指定通知
    deleted_count, _ = Notification.objects.filter(id__in=notification_ids, recipient=request.user).delete()

    return Response({'status': 'success', 'deleted_count': deleted_count})
